// Copyright  2011, 2012 Petr TALLA. [petr.talla@gmail.com]
//
// This file is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License
// as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This file is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY;  without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU Lesser General Public License for more details.
// [http://www.gnu.org/copyleft/lesser.html]
//=============================================================================
#include "./TcHtmlView.h"
#include <TcCmdTransl.h>
#include <QVariant>
#include <QUrl>
#include <TcCmdTransl.h>
#include <TcCmdEngine.h>
#include <QWebFrame>
#include <TcLock.h>
#include <assert.h>

//=============================================================================
TcHtmlView::TcHtmlView()
{   page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);
    QObject::connect(this, SIGNAL(linkClicked(const QUrl&)), this, SLOT(urlHandler_(const QUrl&)));

    //page()->mainFrame()->addToJavaScriptWindowObject("viewxx", this);
}

TcHtmlView::~TcHtmlView()
{
}

void TcHtmlView::execute(QVariant cmd)
{   TcLock lock;
    TcCmdTransl::xcall(cmd.toByteArray(), true);
    //TcCmdTransl::xcall("tab_set_commands");
}

//=============================================================================
void TcHtmlView::urlHandler_(const QUrl& url)
{

#ifndef NDEBUG
    QString scheme = url.scheme();
    QString fragment = url.fragment();
    QString host = url.fragment();
    QString path = url.fragment();
    QString query = url.fragment();
#endif

    if (url.scheme() == "tcview" )
    {

        TcLock lock;

        QString cmd(QUrl::fromPercentEncoding(url.encodedFragment()));

        TcCmdTransl transl(cmd.toUtf8().data()); //TODO no conversion here !

        while (transl.result_.items_.empty() == false)
        {
            TcArgCol* coli = transl.result_.items_.front()->getAsCol();
            transl.result_.items_.pop_front();
            if (coli == NULL) { assert(0); continue; }
            TcCmdEngine::engine().execute(coli, true);
        }

    }
    else
    {   QString URL = url.toString();
        setUrl(URL);
        page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);
    }
}

//=============================================================================
